<template>
  <div>
    <div class="title">
      <div class="basetxt">商品属性设置</div>
      <div class="basebtn">
        <el-button size="mini" type="primary" plain round @click="onAttrParamRefresh">刷新</el-button>
        <el-button
          size="mini"
          type="primary"
          plain
          round
          :disabled="dcType>0 && list.length==0"
          :loading="isAttributing"
          @click="onSaveSpParamList"
        >保存</el-button>
      </div>
    </div>
    <el-form size="small">
      <el-form-item label="商品属性：">
        <el-radio-group v-model="dcType" style="width:80%;" @change="onTypeClick">
          <el-radio :label="0">无</el-radio>
          <el-radio :label="1">多属性</el-radio>
        </el-radio-group>
      </el-form-item>
      <span v-if="dcType>0">
        <el-row v-for="(att,i) in attArr" :key="i">
          <el-col :span="8">
            <el-form-item label="属性名称：" label-width="95px">
              <el-input
                v-model="att.name"
                style="width:98%;"
                placeholder="请输入属性名"
                @change="onNameChange"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item style="border:1px solid #dddddd;">
              <dynamic-tag :value="att.values" @change="onValueChange" @set="onSetValue(i)"></dynamic-tag>
            </el-form-item>
          </el-col>
          <el-col :span="1" style="text-align:center;margin-top:3px;">
            <el-button
              v-if="i==attArr.length-1 && attArr.length<2"
              size="mini"
              type="text"
              @click.stop="onAddAttribute"
            >
              <i class="el-icon-plus"></i>
            </el-button>
            <el-button
              v-else-if="attArr.length>1"
              size="mini"
              type="text"
              @click.stop="onMinusAttribute(i)"
            >
              <i class="el-icon-minus"></i>
            </el-button>
          </el-col>
        </el-row>
        <el-row class="rcenter" :gutter="2" v-if="list.length>0">
          <el-col :span="2">图片</el-col>
          <el-col :span="8">属性</el-col>
          <el-col :span="2">市场价</el-col>
          <el-col :span="2">销售价</el-col>
          <el-col :span="2">裸价</el-col>
          <el-col :span="2">运费</el-col>
          <el-col :span="2">锐费</el-col>
          <el-col :span="2">成本价</el-col>          
          <el-col :span="2">库存</el-col>
        </el-row>
        <draggable v-model="list">
          <div class="sx" v-for="(param,i) in list" :key="i+new Date()">
            <el-row class="rcenter" :gutter="2">
              <!--1图片-->
              <el-col :span="2">
                <select-pic
                  :pics="pics"
                  :value="param.DefaultProductFileID"
                  @change="onLogoChange"
                  @set="onLogoSet(i)"
                ></select-pic>
              </el-col>
              <!--2属性-->
              <el-col :span="8">{{GetAttributeVal(param)}}</el-col>
              <!--3市场价-->
              <el-col :span="2">
                <el-input-number
                  v-model="param.PriceMarket"
                  size="small"
                  :min="0"
                  :precision="2"
                  :controls="false"
                ></el-input-number>
              </el-col>
              <!--4销售价-->
              <el-col :span="2">
                <el-input-number
                  v-model="param.PriceSell"
                  size="small"
                  :min="0"
                  :precision="2"
                  :controls="false"
                ></el-input-number>
              </el-col>
              <!--5裸价-->
              <el-col :span="2">
                <el-input-number
                  v-model="param.PriceNet"
                  size="small"
                  :min="0"
                  :precision="2"
                  :controls="false"
                ></el-input-number>
              </el-col>
              <!--6运费-->
              <el-col :span="2">
                <el-input-number
                  v-model="param.PricePost"
                  size="small"
                  :min="0"
                  :precision="2"
                  :controls="false"
                ></el-input-number>
              </el-col>
              <!--7锐费-->
              <el-col :span="2">
                <el-input-number
                  v-model="param.PriceTax"
                  size="small"
                  :min="0"
                  :precision="2"
                  :controls="false"
                ></el-input-number>
              </el-col>
              <!--8成本价-->
              <el-col :span="2">
                <el-input-number
                  v-model="param.PriceCost"
                  size="small"
                  :min="0"
                  :precision="2"
                  :controls="false"
                ></el-input-number>
              </el-col>
              <!--9库存-->
              <el-col :span="2">
                <el-input-number
                  v-model="param.Stock"
                  size="small"
                  :min="0"
                  :precision="0"
                  :controls="false"
                  @change="onStockChange(i)"
                ></el-input-number>
              </el-col>
            </el-row>
          </div>
        </draggable>
      </span>
    </el-form>
  </div>
</template>
<script>
import {
  saveProductParamList //url: '/produce/SaveProductParamList - 保存商品属性信息
} from "@/api/product";
import { multiCartesian } from "@/api/common"; //笛卡尔积
import dynamicTag from "@/components/BasicType/tag_dynamic"; //src\components\BasicType\tag_dynamic.vue
import draggable from "vuedraggable"; //拖动排序
import selectPic from "@/components/picture/selectPic"; //src\components\picture\c.vue

export default {
  props: {
    spId: { type: Number, default: 0 },
    params: { type: Object }, //属性参数母板
    attribute: { type: Object },
    pics: {
      type: Array,
      default: function() {
        return [];
      }
    },
    isFlowMoreAttr:{type:Boolean,default:true},//暂未启用：默认为真
    refresh:{type:Boolean}
  },
  components: {
    dynamicTag,
    draggable,
    selectPic
  },
  data() {
    return {
      dcType: 0, //属性个数
      attArr: [{ name: "", values: [] }],
      list: [], //子产品列表

      isAttributing: false,
      temp: { name: "", values: [] }, //元素模板

      dcValue: [], //当前修改的属性值的暂存
      file_id: 0 //当前选中图标的ID-返回用
    };
  },
  created() {
    // console.log('创建:');
    setTimeout(() => {
      this.SetAttribute(this.$props.attribute);
    }, 500);
  },
  watch: {
    //通过该参数：无论上级数据【attribute】是否变化，都会视为变化的
    refresh:function(){
      this.SetAttribute(this.$props.attribute);
    }
  },
  methods: {
    onTypeClick(nval) {
      this.$emit("dc-type", nval > 0 ? 1 : 0);
      if (nval == 1 && this.attArr.length == 0) {
        this.attArr.push(JSON.parse(JSON.stringify(this.temp)));
      }
    },
    SetAttribute(val) {
      this.dcType = val.type > 0 ? 1 : 0;
      this.attArr = val.attr;
      this.list = val.list;
      // console.log(this.dcType);
    },
    onAttrParamRefresh() {
      this.$emit("refresh"); //通知上级读取最新数据
      // console.log('刷新:');
      //  //如果参数无变化，自己重设
    },
    //添加属性
    onAddAttribute() {
      this.attArr.push(JSON.parse(JSON.stringify(this.temp)));
      this._SetList();
    },
    //删除属性
    onMinusAttribute(i) {
      this.attArr.splice(i, 1);
      this._SetList();
    },
    //保存商品属性列表===================================================
    onSaveSpParamList() {
      if (this.dcType == 1 && !this.isFlowMoreAttr) {
        let zs = this._CalcTotalStock(this.list, 0, this.list.length);
        if (zs !== this.$props.params.stock) {
          this.$message.error(
            "多属性产品【库存总和】与【商品总库存】不等，请调整后再保存！"
          );
          return;
        }
      }
      this.$confirm("此操作将属性参数设置内容, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this._SaveSpParamList();
        })
        .catch();
    },
    _SaveSpParamList() {
      this.isAttributing = true;
      let data = [];
      if (this.dcType > 0) {
        this.list.forEach((att, i) => {
          att.OrderNum = i + 1;
        });
        data = this.list;
      }
      saveProductParamList({
        sp_id: this.$props.spId, //商品ID
        dc_type: this.dcType, //当前属性类型：0无 1多属性
        type: this.attArr.length, //属性的个数
        list: data //子产品列表,真实销量编辑处不保存，由销售处更新
      }).then(r => {
        if (r.code == 0) {
          this.$emit("save-ok");
          this.$message.success("商品属性保存成功！");          
        } else {
          this.$message.success("商品属性保存出错！原因：" + r.msg);
        }
        this.isAttributing = false;
      });
    },
    //当子产品库存变化时
    onStockChange(k) {
      let kStock = this.list[k].Stock;
      if (typeof kStock == "undefined") this.list[k].Stock = 0; //如果第K个为空了，调整为0
      let mbStock = this.$props.params.stock; //母板的库存：总库存
      let totalStock = this._CalcTotalStock(this.list, 0, this.list.length);
      if (this.$props.isFlowMoreAttr) {
        this.$emit("stock-change", totalStock); //返回新的总库存
      } else {
        let tStock = this._CalcTotalStock(this.list, 0, this.list.length - 1); //除最后一个的库存总和
        if (tStock > mbStock) {
          //大于母板的
          this.$message.error(
            "多属性产品库存超过了商品的库存总额，请重新输入！"
          );
        } else {
          this.list[lastIndex].Stock = mbStock - tStock;
        }
      }
    },
    //属性的图标更改-该事件先于【onLogoClick】----------------------------------------------
    onLogoChange(fileId) {
      this.file_id = fileId;
    },
    //属性图标更改后写入list对应的元素中-该事件需在【onLogoChange】之后
    onLogoSet(i) {
      this.list[i].DefaultProductFileID = this.file_id;
    },
    //以下为手动设置属性名及其值时的生成子产品列表=====================================================
    //根据属性参数数组【attArr】生成属性子商品列表【list】-----------------------------
    _SetList() {
      let isCalcList = true; //是否计算子产品列表
      let data = []; //计算笛卡尔积的原对象，格式：[['a', 'b', 'c'], [1, 2, 3, 4], ['A', 'B'], ['#', '@', '+'], ['Mary', 'Terry', 'KYO']]

      this.attArr.forEach(att => {
        //只要有一个属性名或其值为空，均不生成子产品列表
        isCalcList = isCalcList && !(att.name == "" || att.values.length == 0);
        data.push(att.values);
      });

      this.list = []; //清空原有子产品
      // this.$emit("list清空了");
      if (!isCalcList) {
        return; //不计算子产品列表
      }

      //计算多属性的笛卡尔积
      let attCarList = multiCartesian(data);
      let params = this.$props.params; //母板
      attCarList.forEach((val, i) => {
        //初始化一个子产品的三个参数
        let n = [],
          v = [];
        for (let j = 0; j < 3; j++) {
          n.push("");
          v.push("");
        }
        //三个参数填入相应值
        let pms = val.toString().split(",");
        pms.forEach((pm, i) => {
          n[i] = this.attArr[i].name; //参数名
          v[i] = pm;
        });

        //生成一个子产品
        let spParamInfo = {
          ProductParamID: 0, //序号 - 自动生成
          ProductDataID: params.product_id, //产品序号
          ParamDefault: 0, //参数母版 - 0不是  1是
          OrderNum: 0, //排序号
          ParamName1: n[0], //参数名称
          ParamValue1: v[0], //参数值
          ParamName2: n[1], //参数名称2
          ParamValue2: v[1], //参数值2
          ParamName3: n[2], //参数名称3
          ParamValue3: v[2], //参数值3
          PriceMarket: params.price_market, //市场价
          PriceSell:params.price_sell,//销售价
          PriceNet: params.price_net, //裸价
          PriceTax: params.price_tax, //税费
          PricePost: params.price_post, //运费
          PriceCost: params.price_cost, //成本价
          CoinDeduct: params.coin_deduct, //抵扣币值(积分)
          Stock: i == 0 ? params.stock : 0, //当前库存
          SellSum: 0, //真实销量 - 后台不修改(在产品销售过程中更新，编辑时不修改)
          DefaultProductFileID: params.default_logo_id //默认图标文件ID
        };
        this.list.push(spParamInfo);
      });
    },
    //属性名更改--------------------------------------------------------------------
    onNameChange() {
      this._SetList();
    },
    //暂存属性值的更改1111
    onValueChange(values) {
      this.dcValue = values;
      // console.log(this.dcValue);
    },
    //更新属性值的更改1111
    onSetValue(i) {
      this.attArr[i].values = this.dcValue;
      this._SetList();
    },
    //======================================================================
    GetAttributeVal(param) {
      if (
        param.ParamValue1 !== "" &&
        param.ParamValue2 !== "" &&
        param.ParamValue3 !== ""
      ) {
        return (
          param.ParamValue1 + "-" + param.ParamValue2 + "-" + param.ParamValue3
        );
      } else if (param.ParamValue1 !== "" && param.ParamValue2 !== "") {
        return param.ParamValue1 + "-" + param.ParamValue2;
      } else if (param.ParamValue1 !== "") {
        return param.ParamValue1;
      } else {
        return "";
      }
    },
    //计算多属性新产品的总库存
    _CalcTotalStock(list, start, len) {
      let zs = 0;
      if (start > list.length - 1 || start + len > list.length) {
        return zs;
      }
      for (var i = start; i < start + len; i++) {
        zs += list[i].Stock;
      }
      return zs;
    }
  }
};
</script>
<style lang="scss" scoped>
.title {
  height: 26px;
  border-bottom: 2px solid rgb(11, 11, 78);
  margin-top: 10px;
  margin-bottom: 5px;
  .basetxt {
    float: left;
    font-size: 16px;
    border: 1px solid rgb(11, 11, 78);
    color: white;
    background-color: rgb(11, 11, 78);
  }
  .edittxt {
    margin-top: 10px;
  }
  .basebtn {
    float: right;
    margin-top: -4px;
  }
}
.sx {
  line-height: 52px;
  height: 52px;
  margin-bottom: 2px;
}
.sx:nth-child(2n) {
  background-color: rgb(243, 243, 243);
}
.sx:nth-child(2n + 1) {
  background-color: rgb(230, 230, 230);
}
.rcenter {
  text-align: center;
}
.el-input-number {
  width: 100%;
}
</style>